# !/bin/bash

###     Utility Functions     #################################################
function is_opencv_installed() {
    if dpkg -l | grep -q "libopencv-dev"; then
        # echo "libopencv-dev installed."
        return 0
    else
        # echo "libopencv-dev not installed."
        return 1
    fi
}

function get_opencv_version() {
    local version
    version=$(pkg-config --modversion opencv4 2>/dev/null)
    if [ -n "$version" ]; then
        echo -e "Found OpenCV version: $version"
    else
        echo -e "Found OpenCV version: None"
    fi
}
###############################################################################

if [ ! -d onnx ]; then
    mkdir onnx
    
    pip install huggingface_hub onnxruntime -i https://mirrors.aliyun.com/pypi/simple
    export HF_ENDPOINT=https://hf-mirror.com
    huggingface-cli download --resume-download onnx-community/YOLOv10 yolov10n.onnx --local-dir onnx
fi


if [ ! -d onnxruntime ]; then
    git clone --recursive https://github.com/Microsoft/onnxruntime.git
    pushd onnxruntime
    git checkout v1.21.1
    ./build.sh --config Release --build_shared_lib --parallel --allow_running_as_root
    popd
fi

###############################################################################
script_path="${BASH_SOURCE[0]}"
# get script abs directory
while [ -h "$script_path" ]; do
    script_dir="$(cd -P "$(dirname "${script_path}")" >/dev/null 2>&1 && pwd)"
    script_path="$(readlink "$script_path")"
    [[ $script_path != /* ]] && script_path="$script_dir/$script_path"
done
script_dir="$(cd -P "$(dirname "${script_path}")" >/dev/null 2>&1 && pwd)"

project_dir=$(realpath $(dirname "${script_dir}"))
echo -e "Found project DIR_PATH: \033[32m $project_dir \033[0m"
########################################################################

if is_opencv_installed; then
    get_opencv_version
else
    apt install libopencv-dev -y
fi

if [ -d onnxruntime ]; then
    if [ ! -d build ]; then
        mkdir build
    fi

    pushd build
    rm -rf *
    cmake .. -DBUILD_EXAMPLES_NPU=OFF -DBUILD_EXAMPLES_CPU=ON && make -j
    ./yolov10_sample_cpu ${project_dir}/examples/cv/detection/assets/bus.jpg ${project_dir}/examples/onnx/yolov10n.onnx 
    popd

else
    echo -e "Found onnxruntime DIR_PATH: \033[32m False \033[0m"
fi